<template>
  <div ref="chartRef" class="chart realtime-spectrum"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from "vue"
import * as echarts from "echarts"

// ========== refs ==========
const chartRef = ref(null)
let chartInstance = null
let timer = null

// ========== 模拟频率轴 ==========
const frequencies = Array.from({ length: 100 }, (_, i) => 470 + i * 3)
const freqLabels = frequencies.map(f => f.toFixed(1))

// ========== 生成随机 dBm 数据 ==========
function generateRandomDbData() {
  return frequencies.map(() => {
    const base = -100 + Math.random() * 20
    if (Math.random() < 0.03) {
      return -50 + Math.random() * 10 // 强信号突起
    }
    return base
  })
}

// ========== 频段标记 ==========
function getAxisLabel(target) {
  const closest = frequencies.reduce((a, b) =>
    Math.abs(b - target) < Math.abs(a - target) ? b : a
  )
  return closest.toFixed(2)
}

function generateMarkAreaData() {
  const bands = [
    {
      label: "WRC07-1分配",
      start: 470,
      end: 500
    },
    {
      label: "WRC07-2分配",
      start: 500,
      end: 550
    },
    {
      label: "广电占用",
      start: 550,
      end: 600
    },
    {
      label: "广电-2占用",
      start: 600,
      end: 650
    },
    {
      label: "非运营商",
      start: 650,
      end: 700
    },
    {
      label: "WRC07-3分配",
      start: 700,
      end: 770
    }
  ]
  const colors = ["#00bcd4", "#2196f3", "#4caf50", "#ff9800", "#9c27b0", "#f44336"]
  return bands.map((band, index) => {
    const startLabel = getAxisLabel(band.start)
    const endLabel = getAxisLabel(band.end)
    return [
      {
        name: band.label,
        xAxis: startLabel,
        itemStyle: { color: colors[index % colors.length] },
        label: {
          show: true,
          position: "insideTop",
          formatter: band.label,
          fontSize: 10,
          fontWeight: "bold",
          color: "#fff"
        }
      },
      { xAxis: endLabel }
    ]
  })
}

// ========== 初始化图表（固定尺寸，无需重试） ==========
async function initChart() {
  await nextTick()

  const el = chartRef.value
  if (!el) {
    return
  }

  // 因为样式已设为固定宽高，这里直接初始化
  chartInstance = echarts.init(el)

  const option = {
    title: {
      text: "实时频谱（3秒更新）",
      left: "center",
      textStyle: { color: "#fff" }
    },
    tooltip: {
      trigger: "axis",
      formatter: (params) => {
        const freq = params[0].name
        const db = params[0].value
        return `频率: ${freq} MHz<br/>强度: ${db?.toFixed(2) ?? "N/A"} dBm`
      }
    },
    xAxis: {
      type: "category",
      data: freqLabels,
      name: "频率 (MHz)",
      axisLabel: {
        margin: 20,
        fontSize: 12,
        color: "#ccc"
      },
      splitLine: { show: false }
    },
    yAxis: {
      type: "value",
      name: "dBm",
      min: -110,
      max: -40,
      axisLabel: { color: "#ccc" }
    },
    series: [{
      type: "line",
      data: generateRandomDbData(),
      smooth: true,
      showSymbol: false,
      lineStyle: {
        color: "#00ffff",
        width: 2
      },
      areaStyle: { color: "rgba(0, 255, 255, 0.2)" },
      markArea: {
        data: generateMarkAreaData(),
        silent: true
      }
    }],
    grid: {
      top: 40,
      bottom: 60,
      left: 50,
      right: 30
    }
  }

  chartInstance.setOption(option)

  // 每3秒更新一次数据
  timer = setInterval(() => {
    const newData = generateRandomDbData()
    chartInstance.setOption({
      series: [{ data: newData }]
    })
  }, 3000)

  window.addEventListener("resize", handleResize)
}

function handleResize() {
  chartInstance?.resize()
}

onMounted(() => {
  initChart()
})

onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer)
  }
  window.removeEventListener("resize", handleResize)
  chartInstance?.dispose()
})
</script>

<style scoped>
/* 👇 关键：固定宽高 */
.chart {
  width: 1000px; /* 固定宽度 */
  height: 600px; /* 固定高度 */
  background: #597086;
  border-radius: 6px;
  margin: 0 auto; /* 居中显示（可选） */
}
</style>
